<?php

class CpagentController extends Core_Controller_Action 
{
	private $_vat;
	
	public function init() {
	
		$this->_vat = new Vat();
	}
	
	public function indexAction() {
		$this->_forward( 'raports', 'cpagent' );
	}

	public function raportsAction() {
		$Invitation = new Invitation();
		$page = intval( $this->_getParam( 'page' ) );
		
		if( $this->_request->isPost() ) {
			$post = $this->_request->getPost();
			
			if( $post['from'] || $post['to'] ) {
				$Users = new Users();
				
				$post['from'] = empty( $post['from'] ) ? false : $post['from'];
				$post['to'] = empty( $post['to'] ) ? false : $post['to'];
				
				$this->view->from = $post['from'];
				$this->view->to = $post['to'];
				
				$this->view->raportList = $Users->salesReport( $this->userData->u_id, $post['from'], $post['to'] );
			}
		} else {
			
			$pagerLayout = $Invitation->getListWithPager( $this->userData->u_id ,$page, $this->view->baseUrl() );
			$this->view->list = $pagerLayout->execute();
			$this->view->pager = $pagerLayout;
		
		}
		
		$this->assignType( 0 );
	}

	public function invitationAction() {
		
		if( $this->_request->isPost() ) {
			$post = $this->_request->getPost();

			$emails = explode( ';', $post['email'] );
			
			foreach( $emails as $email ) {
				if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
					$Invitation = new Invitation();
					$Invitation->users_u_id = $this->userData->u_id;
					$Invitation->email = $email;
					$Invitation->add_date = Date( 'Y-m-d H:i:s' );
					$Invitation->save();
					
					$url = $this->serverName . $this->view->baseUrl() . '/index/newaccount/u/' . $this->userData->u_id . '/m/' . $email;
			
					$mail = new Core_Mail();
					$mail->addTo( $email, $email );
					$mail->setFrom( 'no-reply@carnauba.pl', 'Carnauba' );
					$mail->setSubject( $post['title'] );
					
					$body  = nl2br( $post['body'] );
					$body .= '<br /><a href="' . $url . '">' . $url . '</a>';
					
					$mail->setBodyHtml( $body );
					$mail->send();
				}
			}
			
			$this->_redirect( 'cpagent/invitation/oper/6' );
		}
		
		$this->assignType( 1 );
	}

	public function assignType( $type ) {
		
		$this->view->type = $type;
		
		switch( $type ) {
			case 0 :
				$this->view->yih2 = 'Raporty';
				break;
			case 1 :
				$this->view->yih2 = 'Zaproszenia';
				break;
		}
	}
}